<template>
  <div class="sidebar-container" ref="sidebarRef">
    <div
      class="sidebar-item"
      v-for="(item, index) in sideMenuItems"
      :key="item.id"
      :class="{ active: activeMenu === index }"
      @click="toggleSubMenu(index)"
      ref="menuItemsRef"
    >
      <div class="sidebar-item-icon">
        <IconFont class="icon" :name="item.icon" size="1.5625vw" />
      </div>
      <div class="sidebar-item-text">{{ item.text }}</div>
    </div>

    <div
      class="submenu-container"
      v-if="activeMenu !== null"
      ref="submenuRef"
      :style="submenuStyle"
    >
      <component :is="currentSubmenuComponent" @close-submenu="closeSubmenu"></component>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import ModelLibrary from './submenus/ModelLibrary/Index.vue'
import MeasurementLibrary from './submenus/MeasurementLibrary/Index.vue'
import PlottingLibrary from './submenus/PlottingLibrary/Index.vue'
import EffectsLibrary from './submenus/EffectsLibrary/Index.vue'
import AnalysisLibrary from './submenus/AnalysisLibrary/Index.vue'
import GraphicsLibrary from './submenus/GraphicsLibrary/Index.vue'
import { useStartAnalysisStore } from '@/stores/startAnalysis.js'
const startAnalysisStore = useStartAnalysisStore()

// 菜单数据
const sideMenuItems = ref([
  {
    id: 'model',
    text: '模型库',
    icon: 'moxing',
    component: 'ModelLibrary',
  },
  {
    id: 'measurement',
    text: '测量库',
    icon: 'celiang',
    component: 'MeasurementLibrary',
  },
  {
    id: 'plotting',
    text: '标绘库',
    icon: 'biaohui',
    component: 'PlottingLibrary',
  },
  {
    id: 'specialEffects',
    text: '特效库',
    icon: 'texiao',
    component: 'EffectsLibrary',
  },
  {
    id: 'analysis',
    text: '分析库',
    icon: 'fenxi',
    component: 'AnalysisLibrary',
  },
  {
    id: 'graph',
    text: '矢量库',
    icon: 'ht',
    component: 'GraphicsLibrary',
  },
])

// 当前激活的菜单索引
const activeMenu = ref(null)

// 添加关闭子菜单的方法
const closeSubmenu = () => {
  activeMenu.value = null
}

// 侧边栏和子菜单的DOM引用
const sidebarRef = ref(null)
const submenuRef = ref(null)
const menuItemsRef = ref([])

// 子菜单样式计算
const submenuStyle = ref({})

// [MODIFIED] 更新子菜单位置
const updateSubmenuPosition = async () => {
  if (activeMenu.value === null) return
  await nextTick()
  const activeItem = menuItemsRef.value[activeMenu.value]
  if (!activeItem || !submenuRef.value) return

  const activeItemRect = activeItem.getBoundingClientRect()
  const sidebarRect = sidebarRef.value.getBoundingClientRect()

  // 重新计算子菜单位置
  submenuStyle.value = {
    position: 'absolute',
    // 将子菜单放在侧边栏的左侧，水平位置正确
    right: `${sidebarRect.width + (window.innerWidth * 0.5208) / 100}px`,
    // 关键修正：计算子菜单的 top 值，使其与点击的菜单项顶部对齐
    top: `${activeItemRect.top - sidebarRect.top}px`,
    transform: 'translateX(0)',
    // 关键修正：调整变换原点以适应新的顶部对齐方式
    transformOrigin: 'right top',
  }
}

// 切换子菜单显示状态
const toggleSubMenu = async (index) => {
  if (activeMenu.value === index) {
    activeMenu.value = null
  } else {
    activeMenu.value = index
    updateSubmenuPosition()
  }
}

// 当前显示的子菜单组件
const currentSubmenuComponent = computed(() => {
  if (activeMenu.value === null) return null
  const componentName = sideMenuItems.value[activeMenu.value].component
  switch (componentName) {
    case 'ModelLibrary':
      return ModelLibrary
    case 'MeasurementLibrary':
      return MeasurementLibrary
    case 'PlottingLibrary':
      return PlottingLibrary
    case 'EffectsLibrary':
      return EffectsLibrary
    case 'AnalysisLibrary':
      return AnalysisLibrary
    case 'GraphicsLibrary':
      return GraphicsLibrary
    default:
      return null
  }
})

// 处理全局点击事件
const handleClickOutside = (event) => {
  if (activeMenu.value === null) return
  if (startAnalysisStore.startAnalysisState) return
  const isClickInSidebar = sidebarRef.value && sidebarRef.value.contains(event.target)
  const isClickInSubmenu = submenuRef.value && submenuRef.value.contains(event.target)
  if (!isClickInSidebar && !isClickInSubmenu) {
    activeMenu.value = null
  }
}

// 监听窗口大小变化，更新子菜单位置
const handleResize = () => {
  updateSubmenuPosition()
}

// 监听activeMenu变化
watch(activeMenu, () => {
  updateSubmenuPosition()
})

// 挂载和卸载事件监听器
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
  window.addEventListener('resize', handleResize)
  updateSubmenuPosition()
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
  window.removeEventListener('resize', handleResize)
})
</script>

<style lang="scss" scoped>
.sidebar-container {
  position: absolute;
  z-index: 2;
  top: 7.2917vw /* 140px -> 7.2917vw */;
  right: 1.0417vw; /* 20px -> 1.0417vw */
  width: 3.9583vw /* 76px -> 3.9583vw */;
  background-color: rgba(0, 8, 26, 0.7);
  border-radius: 0.4167vw; /* 8px -> .4167vw */
  box-shadow: 0 0 0.5208vw /* 10px -> .5208vw */ rgba(0, 195, 255, 0.5);
  border: 0.0521vw /* 1px -> .0521vw */ solid rgba(0, 195, 255, 0.6);
  overflow: visible;
  display: flex;
  flex-direction: column;
  gap: 0.4167vw /* 8px -> .4167vw */;
  padding: 0.4167vw /* 8px -> .4167vw */;
  animation: submenuFadeIn 0.6s cubic-bezier(0.16, 1, 0.3, 1) forwards;

  .sidebar-item {
    width: 3.125vw /* 60px -> 3.125vw */;
    height: 3.125vw /* 60px -> 3.125vw */;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    gap: 0.3125vw /* 6px -> .3125vw */;
    cursor: pointer;
    position: relative;
    border-radius: 0.2604vw;
    transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
    &:hover {
      background-color: rgba(0, 195, 255, 0.2);
      .sidebar-item-icon {
        .icon {
          scale: 0.9;
        }
      }
    }

    &.active {
      background-color: rgba(0, 195, 255, 0.3);
      box-shadow: 0 0 0.3125vw rgba(0, 195, 255, 0.8);
    }

    .sidebar-item-icon {
      .icon {
        width: 1.5625vw /* 30px -> 1.5625vw */;
        height: 1.5625vw /* 30px -> 1.5625vw */;
        object-fit: contain;
        transition: all 0.5s;
      }
    }

    .sidebar-item-text {
      height: 1.0417vw; /* 20px -> 1.0417vw */
      line-height: 1.0417vw; /* 20px -> 1.0417vw */
      font-size: 0.7292vw /* 14px -> .7292vw */;
      color: #fff;
    }
  }
}

@keyframes submenuFadeIn {
  from {
    opacity: 0;
    transform: translateX(10.4167vw);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}
</style>
